"use client"

import { useState, useRef, useEffect } from "react"
import {
    View,
    Text,
    StyleSheet,
    TextInput,
    TouchableOpacity,
    Image,
    Platform,
    Alert,
    KeyboardAvoidingView,
    ScrollView,
    Dimensions,
} from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { LinearGradient } from "expo-linear-gradient"
import { theme } from "../constants/theme"
import { useRouter } from "expo-router"
import Animated, { FadeInDown, FadeInUp } from "react-native-reanimated"
import { Lock, Smartphone } from "lucide-react-native"

const { width, height } = Dimensions.get("window")

export default function LoginScreen() {
    const router = useRouter()
    const [phoneNumber, setPhoneNumber] = useState("")
    const [verificationCode, setVerificationCode] = useState("")
    const [countdown, setCountdown] = useState(0)
    const [errors, setErrors] = useState<{ phone?: string; code?: string }>({})
    const intervalRef = useRef<NodeJS.Timeout | null>(null)
    const codeInputRef = useRef<TextInput>(null)

    // 清理倒计时
    useEffect(() => {
        return () => {
            if (intervalRef.current) {
                clearInterval(intervalRef.current)
            }
        }
    }, [])

    // 处理获取验证码
    const handleGetCode = () => {
        // 验证手机号
        if (!phoneNumber.trim()) {
            setErrors({ ...errors, phone: "请输入手机号" })
            return
        }

        if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
            setErrors({ ...errors, phone: "请输入有效的手机号" })
            return
        }

        // 模拟发送验证码
        Alert.alert("验证码已发送", `验证码已发送至 ${phoneNumber}`, [
            { text: "确定", onPress: () => codeInputRef.current?.focus() },
        ])

        // 开始倒计时
        setCountdown(60)
        if (intervalRef.current) {
            clearInterval(intervalRef.current)
        }

        intervalRef.current = setInterval(() => {
            setCountdown((prev) => {
                if (prev <= 1) {
                    if (intervalRef.current) {
                        clearInterval(intervalRef.current)
                    }
                    return 0
                }
                return prev - 1
            })
        }, 1000)
    }

    // 处理登录
    const handleLogin = () => {
        const newErrors: { phone?: string; code?: string } = {}

        if (!phoneNumber.trim()) {
            newErrors.phone = "请输入手机号"
        } else if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
            newErrors.phone = "请输入有效的手机号"
        }

        if (!verificationCode.trim()) {
            newErrors.code = "请输入验证码"
        } else if (!/^\d{6}$/.test(verificationCode)) {
            newErrors.code = "验证码格式不正确"
        }

        setErrors(newErrors)

        if (Object.keys(newErrors).length === 0) {
            // 模拟登录成功
            Alert.alert("登录成功", "欢迎回来！", [
                { text: "确定", onPress: () => router.replace("/(tabs)/vocabulary-screen") },
            ])
        }
    }

    // 处理隐私政策和服务条款
    const handlePrivacyPolicy = () => {
        router.push("/my/privacy-policy")
    }

    const handleTermsOfService = () => {
        router.push("/my/terms-of-service")
    }

    return (
        <View style={styles.container}>
            {/* 背景渐变 - 覆盖整个屏幕 */}
            <LinearGradient
                colors={["rgba(91, 142, 244, 0.2)", "rgba(255, 255, 255, 1)"]}
                style={styles.backgroundGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 0.4 }}
            />

            <SafeAreaView style={styles.safeArea} edges={["bottom", "left", "right"]}>
                <KeyboardAvoidingView
                    behavior={Platform.OS === "ios" ? "padding" : "height"}
                    style={styles.keyboardAvoidingView}
                >
                    <ScrollView
                        contentContainerStyle={styles.scrollContent}
                        showsVerticalScrollIndicator={false}
                        keyboardShouldPersistTaps="handled"
                    >
                        {/* Logo和标题 */}
                        <Animated.View style={styles.logoContainer} entering={FadeInDown.delay(200).springify()}>
                            <Image source={{ uri: "https://cdn-icons-png.flaticon.com/512/3135/3135755.png" }} style={styles.logo} />
                            <Text style={styles.appName}>育儿英文教育</Text>
                            <Text style={styles.slogan}>让孩子爱上英语学习</Text>
                        </Animated.View>

                        {/* 登录表单 */}
                        <Animated.View style={styles.formCard} entering={FadeInUp.delay(300).springify()}>
                            <Text style={styles.welcomeText}>欢迎登录</Text>
                            <Text style={styles.welcomeDescription}>请使用手机号登录或注册账号</Text>

                            {/* 手机号输入 */}
                            <View style={styles.inputContainer}>
                                <View style={[styles.inputWrapper, errors.phone ? styles.inputError : null]}>
                                    <Smartphone size={20} color={theme.colors.neutral.gray} style={styles.inputIcon} />
                                    <TextInput
                                        style={styles.input}
                                        placeholder="请输入手机号"
                                        placeholderTextColor="#AAAAAA"
                                        keyboardType="phone-pad"
                                        value={phoneNumber}
                                        onChangeText={(text) => {
                                            setPhoneNumber(text)
                                            if (errors.phone) {
                                                setErrors({ ...errors, phone: undefined })
                                            }
                                        }}
                                        maxLength={11}
                                    />
                                </View>
                                {errors.phone && <Text style={styles.errorText}>{errors.phone}</Text>}
                            </View>

                            {/* 验证码输入 */}
                            <View style={styles.inputContainer}>
                                <View style={[styles.inputWrapper, errors.code ? styles.inputError : null]}>
                                    <Lock size={20} color={theme.colors.neutral.gray} style={styles.inputIcon} />
                                    <TextInput
                                        ref={codeInputRef}
                                        style={styles.input}
                                        placeholder="请输入验证码"
                                        placeholderTextColor="#AAAAAA"
                                        keyboardType="number-pad"
                                        value={verificationCode}
                                        onChangeText={(text) => {
                                            setVerificationCode(text)
                                            if (errors.code) {
                                                setErrors({ ...errors, code: undefined })
                                            }
                                        }}
                                        maxLength={6}
                                    />
                                    <TouchableOpacity
                                        style={[styles.codeButton, countdown > 0 && styles.codeButtonDisabled]}
                                        onPress={handleGetCode}
                                        disabled={countdown > 0}
                                    >
                                        <Text style={[styles.codeButtonText, countdown > 0 && styles.codeButtonTextDisabled]}>
                                            {countdown > 0 ? `${countdown}秒后重试` : "获取验证码"}
                                        </Text>
                                    </TouchableOpacity>
                                </View>
                                {errors.code && <Text style={styles.errorText}>{errors.code}</Text>}
                            </View>

                            {/* 登录按钮 */}
                            <TouchableOpacity style={styles.loginButton} onPress={handleLogin}>
                                <LinearGradient
                                    colors={theme.colors.primary.gradient}
                                    start={{ x: 0, y: 0 }}
                                    end={{ x: 1, y: 0 }}
                                    style={styles.loginButtonGradient}
                                >
                                    <Text style={styles.loginButtonText}>登录</Text>
                                </LinearGradient>
                            </TouchableOpacity>

                            {/* 隐私政策和服务条款 */}
                            <View style={styles.policyContainer}>
                                <Text style={styles.policyText}>登录即表示您同意</Text>
                                <TouchableOpacity onPress={handlePrivacyPolicy}>
                                    <Text style={styles.policyLink}>《隐私政策》</Text>
                                </TouchableOpacity>
                                <Text style={styles.policyText}>和</Text>
                                <TouchableOpacity onPress={handleTermsOfService}>
                                    <Text style={styles.policyLink}>《服务条款》</Text>
                                </TouchableOpacity>
                            </View>
                        </Animated.View>
                    </ScrollView>
                </KeyboardAvoidingView>
            </SafeAreaView>
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: "rgba(91, 142, 244, 0.2)", // 与渐变起始色相同
    },
    backgroundGradient: {
        position: "absolute",
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
    },
    safeArea: {
        flex: 1,
    },
    keyboardAvoidingView: {
        flex: 1,
    },
    scrollContent: {
        flexGrow: 1,
        paddingBottom: 40,
    },
    logoContainer: {
        alignItems: "center",
        marginTop: height * 0.12,
        marginBottom: height * 0.05,
    },
    logo: {
        width: 100,
        height: 100,
        marginBottom: 16,
    },
    appName: {
        fontSize: 28,
        fontWeight: "bold",
        color: theme.colors.primary.default,
        marginBottom: 8,
    },
    slogan: {
        fontSize: 16,
        color: theme.colors.neutral.darkGray,
    },
    formCard: {
        marginHorizontal: 24,
        backgroundColor: "#FFFFFF",
        borderRadius: 24,
        padding: 24,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 8 },
                shadowOpacity: 0.2,
                shadowRadius: 24,
            },
            android: {
                elevation: 8,
            },
        }),
    },
    welcomeText: {
        fontSize: 24,
        fontWeight: "bold",
        color: theme.colors.neutral.black,
        marginBottom: 8,
    },
    welcomeDescription: {
        fontSize: 14,
        color: theme.colors.neutral.gray,
        marginBottom: 32,
    },
    inputContainer: {
        marginBottom: 20,
    },
    inputWrapper: {
        flexDirection: "row",
        alignItems: "center",
        borderWidth: 1,
        borderColor: "rgba(0, 0, 0, 0.1)",
        borderRadius: 16,
        backgroundColor: "#F8F9FF",
        paddingHorizontal: 16,
    },
    inputError: {
        borderColor: theme.colors.secondary.red.default,
    },
    inputIcon: {
        marginRight: 12,
    },
    input: {
        flex: 1,
        height: 56,
        fontSize: 16,
        color: theme.colors.neutral.black,
    },
    codeButton: {
        paddingHorizontal: 16,
        paddingVertical: 8,
        borderRadius: 8,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
    },
    codeButtonDisabled: {
        backgroundColor: "rgba(0, 0, 0, 0.05)",
    },
    codeButtonText: {
        fontSize: 14,
        fontWeight: "500",
        color: theme.colors.primary.default,
    },
    codeButtonTextDisabled: {
        color: theme.colors.neutral.gray,
    },
    errorText: {
        fontSize: 12,
        color: theme.colors.secondary.red.default,
        marginTop: 4,
        marginLeft: 4,
    },
    loginButton: {
        borderRadius: 16,
        overflow: "hidden",
        marginTop: 16,
        marginBottom: 24,
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 8,
            },
        }),
    },
    loginButtonGradient: {
        paddingVertical: 16,
        alignItems: "center",
        justifyContent: "center",
    },
    loginButtonText: {
        fontSize: 18,
        fontWeight: "600",
        color: "#FFFFFF",
    },
    policyContainer: {
        flexDirection: "row",
        flexWrap: "wrap",
        justifyContent: "center",
        alignItems: "center",
    },
    policyText: {
        fontSize: 12,
        color: theme.colors.neutral.gray,
    },
    policyLink: {
        fontSize: 12,
        color: theme.colors.primary.default,
        fontWeight: "500",
    },
})

